﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Diagnostics;

namespace SuperCalendar.Models
{
    public class EventEntryMeta
    {
        private String _category;

        public String Category
        {
            get { return _category; }
            set { _category = value; }
        }
        private EventPriority _priority;

        public EventPriority Priority
        {
            get { return _priority; }
            set { _priority = value; }
        }
        private int _completed;

        public int Completed
        {
            get { return _completed; }
            set { _completed = value; }
        }

        public EventEntryMeta()
        {
            this._completed = 0;
            this._priority = EventPriority.Normal;
            this._category = "Unkown";
        }

        public EventEntryMeta(String category, EventPriority priority, int completed)
        {
            this._category = category;
            this._priority = priority;
            this._completed = completed;
        }

        public override string ToString()
        {
            XElement meta = new XElement("meta",
                                          new XElement("category", Category),
                                          new XElement("priority", Priority),
                                          new XElement("completed", Completed));
            return meta.ToString();
        }

        public static EventEntryMeta Parse(String metaString)
        {
            EventEntryMeta meta = new EventEntryMeta();
            try
            {
                XElement metaElement = XElement.Parse(metaString);
                try
                {
                    XElement completedElement = metaElement.Element("completed");
                    Debug.Assert(completedElement != null);
                    meta.Completed = Int32.Parse(completedElement.Value);
                }
                catch (Exception ex)
                {
                    throw new ApplicationException("Error to parse event entry meta, wrong formate completed:"+ex);
                }

                XElement categoryElement = metaElement.Element("category");
                Debug.Assert(categoryElement != null);
                meta.Category = categoryElement.Value;

                XElement priorityElement = metaElement.Element("priority");
                Debug.Assert(priorityElement != null);
                meta.Priority = (EventPriority)Enum.Parse(typeof(EventPriority), priorityElement.Value, true);

                return meta;
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Error to parse event entry meta:"+ex);
            }
        }
    }
}
